<template>
  <div>
    <el-row>
      <el-col style="margin-top:3%;margin-left: 14% " :span="17">
        <el-card>
          <el-image v-if="shopdata.commodityImg"
                  style="width: 300px; height: 300px;"
                  :src="'http://localhost:7777/'+shopdata.commodityImg"
                  :preview-src-list="srcList">
          </el-image>
          <div style="margin-left: 36%;margin-top: -28%;width: 300px;height: 300px">
            <h2>{{shopdata.commodityName}}</h2>
            <h3>{{shopdata.commodityIntroduce}}</h3>
            价格<span style="font-size: 25px;color: red">￥{{shopdata.priceRange}}</span>
            <p>地区：{{shopdata.address}}</p>
            <el-radio-group v-for="item in options" v-model="form.informantType" size="mini"
                            @change="aaa(item.label)">
              <el-radio-button
                      style="margin-right: 10px;margin-top: 10px"
                      :value="item.value"
                      :label="item.value"
              >{{item.value}}
              </el-radio-button>
            </el-radio-group>
            <el-col style="margin-top: 10px">
              <el-row>
                <el-button type="danger" plain @click="buy">立即购买</el-button>
                <el-button type="danger" icon="el-icon-shopping-cart-2" @click="cart">加入购物车</el-button>
              </el-row>
            </el-col>
          </div>
          <div style="margin-left: 75%;margin-top: -28%;width: 200px;
              height: 300px;">
            <img v-if="storeData.img"
                 style="margin:0 auto;width: 100px; height: 100px;border-radius:50%"
                 :src="'http://localhost:7777/'+storeData.img"
                 class="image">
            <h4>商店：{{storeData.storeName}}</h4>
            <h4 v-if="storeData.score===''">评分：未评分</h4>
            <h4 v-if="storeData.score!==''">评分：{{storeData.score}}</h4>
            <el-row>
              <template>
                <el-tooltip class="item" effect="dark" content="点我进行聊天" placement="top">
                  <el-button icon="el-icon-loading" circle @click="openDialogChat"/>
                </el-tooltip>
              </template>
            </el-row>
          </div>
        </el-card>
      </el-col>
      <el-col style="margin-top:3%;margin-left: 14% " :span="17">
        <el-tabs type="border-card" v-model="activeName" @tab-click="activeData">
          <el-tab-pane label="商品信息" name="first">
            <el-row :gutter="12">
              <el-col :span="24">
                <el-card shadow="always">
                  <div style="width:80%;margin: 0 auto">
                    店铺名称:<span style="margin-left: 30px">{{shopdata.storeName}}</span><br><br>
                    <span style="font-weight: bold">信息:</span><br>
                    商品名称:<span style="margin-left: 15px">{{shopdata.commodityName}}</span><br>
                    规格参数:<span style="margin-left: 15px">{{shopdata.specs}}</span>
                    <el-button type="text" style="margin-left: 5%" icon="el-icon-caret-right" @click="more">更多详细参数
                    </el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            <el-row :gutter="12">
              <el-col :span="24">
                <el-card shadow="always">
                  <div style="width: 80%;margin: 10px auto">
                    <el-image v-if="urls"
                            style="width: 100%" v-for="url in urls" :key="url" :src="url"/>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="详细规格" name="second">
            <el-row :gutter="12">
              <el-col :span="24">
                <el-card shadow="always">
                  <span style="font-size: 15px">工艺/流行</span><br><br>
                  <table class="mailTable" cellspacing="0" cellpadding="0">
                    <tr>
                      <td class="column">图案</td>
                      <td>{{commodityParams.pattern}}</td>
                    </tr>
                    <tr>
                      <td class="column">细分风格</td>
                      <td>{{commodityParams.subdivisionStyle}}</td>
                    </tr>
                    <tr>
                      <td class="column">服饰工艺</td>
                      <td>{{commodityParams.technology}}</td>
                    </tr>
                  </table>
                </el-card>
              </el-col>
              <el-col :span="24">
                <el-card shadow="always">
                  <span style="font-size: 15px">关键信息</span><br><br>
                  <table class="mailTable" cellspacing="0" cellpadding="0">
                    <tr>
                      <td class="column">面料分类</td>
                      <td>{{commodityParams.fabrics}}</td>
                    </tr>
                    <tr>
                      <td class="column">基础风格</td>
                      <td>{{commodityParams.basic}}</td>
                    </tr>
                    <tr>
                      <td class="column">上市年份季节</td>
                      <td>{{commodityParams.thickness}}</td>
                    </tr>
                    <tr>
                      <td class="column">服饰工艺</td>
                      <td>{{commodityParams.technology}}</td>
                    </tr>
                    <tr>
                      <td class="column">销售渠道类型</td>
                      <td>{{commodityParams.channel}}</td>
                    </tr>
                    <tr>
                      <td class="column">材质成分</td>
                      <td>{{commodityParams.material}}</td>
                    </tr>
                  </table>
                </el-card>
              </el-col>
              <el-col :span="24">
                <el-card shadow="always">
                  <span style="font-size: 15px">其他</span><br><br>
                  <table class="mailTable" cellspacing="0" cellpadding="0">
                    <tr>
                      <td class="column">适用场景</td>
                      <td>{{commodityParams.scene}}</td>
                    </tr>
                    <tr>
                      <td class="column">适用对象</td>
                      <td>{{commodityParams.objects}}</td>
                    </tr>
                  </table>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="累计评价" name="third">
            <el-row v-if="evaluate.length!==0">
              <el-col :span="24" v-for="(evaluate, index) in evaluate" :key="index">
                <el-card :body-style="{ padding: '0px' }">
                  <el-divider><i class="el-icon-mobile-phone"/></el-divider>
                  <span style="padding-left: 10px">{{evaluate.userName}}</span>
                  <el-divider direction="vertical"/>
                  <span>{{evaluate.specs}}</span>
                  <el-divider direction="vertical"/>
                  <span>发布于 {{evaluate.createTime}}</span><br>
                  <span style="padding-left: 10px">{{evaluate.content}}</span><br>
                  <el-image v-if="evaluate.imgList"
                            style="padding-top: 10px;width: 100px;height: 100px;padding-left: 10px"
                            v-for="url in evaluate.imgList" :key="url"
                            :src="url"
                            :preview-src-list="evaluate.imgList">
                  </el-image>
                  <el-divider/>
                </el-card>
              </el-col>
            </el-row>
            <el-alert
                    v-if="evaluate.length===0"
                    title="暂无评论"
                    type="success"
                    center
                    :closable="false">
            </el-alert>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            width="30%"
            >
      <el-card :body-style="{ padding: '0px' }">
        <img v-if="buyData.commodityImg" style="width: 200px;height: 200px" :src="'http://localhost:7777/'+buyData.commodityImg" class="image" alt=""/>
        <div style="padding: 14px;">
          商品名称：<span>{{buyData.commodityName}}</span><br>
          商品价格：<span>{{buyData.commodityPrice}}</span><br>
          商品规格：<span>{{buyData.specs}}</span>
        </div>
      </el-card>
      <span>未开发支付功能，仅供测试使用。</span>
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="buyOK">支付测试</el-button>
  </span>
    </el-dialog>
    <el-dialog
            title="聊天窗口"
            :visible.sync="dialogChat"
            width="43%"
            :close-on-click-modal="false"
            :before-close="closeChat">
      <div class="talk_con">
        <span>{{shopdata.storeName}}</span>
        <div class="talk_show" id="talk_show">
          <div v-if="this.message.length!==0">
            <div v-for="(msg , index) in message" :key='index'>
            <div v-if="msg.sendId===userData.id" class="btalk">
              <span>{{msg.msg}}</span><img v-if="msg.sendImg" style="width: 40px; height: 40px;border-radius:50%"
              :src="'http://localhost:7777/'+msg.sendImg" alt="无"></div>
            <div v-if="msg.sendId!==userData.id" class="atalk">
              <img v-if="msg.sendImg" style="width: 40px; height: 40px;border-radius:50%"
              :src="'http://localhost:7777/'+msg.sendImg" alt="无">
              <span>{{msg.msg}}</span></div>
            </div>
          </div>
        </div>
        <div class="talk_input">
          <input type="text" class="talk_word" v-model="textarea">
          <input type="button" value="发送" class="talk_sub" id="talksub" @click="send">
          <input type="button" value="关闭" class="talk_sub"  @click="closeChat">
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {getToken} from "@/util/auth";
  import {validate} from "@/util/validate";
  import Vue from 'vuex'
  export default {
    name: 'Goods',
    data() {
      return {
        dialogVisible: false,
        dialogChat:false,
        textarea:'',
        message:[],
        CommodityIdDetail: '',
        price: '',
        activeName: 'first',
        form: {
          informantType: "",
        },
        options: [],
        shopdata: '',
        commodityParams: '',
        urls: [],
        list: [],
        srcList: [],
        cId: '',
        storeData: '',
        buyData: '',
        evaluate: [],
        evaluateImg: [],
        userData:{},
        myId:'',
      }
    },
    mounted() {
      this.cid = this.$route.query.id
      this.getCommodityData();
      this.loginUser()
    },
    watch:{
      //监听盒子高度 让新信息处于最低部
      message:function (message) {
        this.$nextTick(() => {
          this.$nextTick(() => {
            let msg = document.getElementById('talk_show'); // 获取对象
            msg.scrollTop = msg.scrollHeight // 滚动高度
          })
        });
      }
    },
    computed: {
    },
    methods: {
      //接收消息
      initWebSocket () {
        // 连接错误
        this.$global.ws.onerror = this.setErrorMessage
        // 连接成功
        this.$global.ws.onopen = this.setOnopenMessage

        // 收到消息的回调
        this.$global.ws.onmessage = this.setOnmessageMessage

        // 连接关闭的回调
        this.$global.ws.onclose = this.setOncloseMessage

        // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = this.onbeforeunload
      },
      setErrorMessage () {
        console.log('WebSocket连接发生错误 状态码：' + this.$global.ws.readyState)
      },
      setOnopenMessage () {
        console.log(this.userData.name+'WebSocket连接成功    状态码：' + this.$global.ws.readyState)
      },
      setOnmessageMessage (event) {
        const datas = JSON.parse(event.data);
        this.message.push(datas)
      },
      setOncloseMessage () {
        console.log(this.userData.name+'WebSocket连接关闭    状态码：' + this.$global.ws.readyState)
      },
      closeWebSocket () {
        this.$global.ws.close()
      },
      onbeforeunload () {
        this.closeWebSocket()
      },

      //关闭
      closeChat(done){
        this.dialogChat = false
        this.$global.ws.close()
        location.reload();
        done();
      },
      //打开聊天窗
      openDialogChat(){
        if (this.userData===undefined){
          this.$message({
            type: "error",
            message: "你还未登录，请先登录!"
          });
          return;
        }
        this.$global.ws.close()
        this.websocket = new WebSocket('ws://localhost:7777/websocket/'
                + this.userData.id);
        this.$global.setWs(this.websocket)
        this.initWebSocket()
        this.dialogChat = true
      },
      //聊天
      send(){
        if (validate(this.textarea)){
          const row = this.storeData;
          const messageDTO = {
            receiveId: row.createUser,
            sendId: this.userData.id,
            sendImg:this.userData.avatar,
            msg: this.textarea
          };
          this.$http({
            method:"post",
            url:"/api/pxx-websocket/sendChatWebSocket",
            params: messageDTO,
          }).then(() => {
            this.message.push(messageDTO)
          });
        }else {
          this.$message.error('不能发空信息哦!');
        }
        this.textarea = ''
      },
      //获取用户信息
      loginUser(){
        var user = getToken();
        if (user===undefined){
          this.userData = user
          return
        }
        this.userData = JSON.parse(user)
      },
      //立即购买
      buyOK() {
        var row = this.buyData
        this.$http({
          method: "post",
          url:"/api/pxx-cart/cart/submit",
          data:JSON.stringify(row),
          headers: {'Content-Type': 'application/json'}
        }).then(() => {
          this.$message({
            type: "success",
            message: "购买成功!"
          });
        }, error => {
          window.console.log(error);
        });
        const messageDTO = {
          receiveId: row.storeId,
          type: '订单推送',
          msg: '您有一个新的订单!'
        };
        this.$http({
          method:"post",
          url:"/api/pxx-websocket/sendOneWebSocket",
          data: messageDTO,
          headers: {'Content-Type': 'application/json'}
        })
        this.dialogVisible = false
      },

      //标签 详细参数  评论
      activeData() {
        var cid = this.cid;
        if (this.activeName === 'second') {
          this.$http({
            methods:"get",
            url:"/api/pxx-params/commodityparams/commodityId",
            params: {
              commodityId: cid
            }
          }).then(res =>{
            this.commodityParams = res.data.data
          });
        }
        if (this.activeName === 'third') {

          this.$http({
            method:"get",
            url:"/api/pxx-evaluate/evaluate/evaluateList",
            params: {
              commodityId: cid
            }
          }).then(res =>{
            this.evaluate = res.data.data
          });

        }
      },
      //点击购买
      buy() {
        if (this.userData===undefined){
          this.$message({
            type: "error",
            message: "你还未登录，请先登录!"
          });
          return;
        }
        if (this.form.informantType === '') {
          this.$message.error("请选择商品规格!");
          return
        }
        this.dialogVisible = true
        var cid = this.cid;
        var row = {
          specs: this.form.informantType,
          storeId: this.shopdata.createUser,
          commodityName: this.shopdata.commodityName,
          commodityPrice: this.price,
          commodityImg: this.shopdata.commodityImg,
          commodityPicture: this.shopdata.commodityPicture,
          storeName: this.shopdata.storeName,
          createUser:this.userData.id,
          updateUser:this.userData.id,
          commodityId: cid,
          status: '3'
        }
        this.buyData = row;
      },
      //加入购物车
      cart() {
        if (this.userData===undefined){
          this.$message({
            type: "error",
            message: "你还未登录，请先登录!"
          });
          return;
        }
        if (this.form.informantType === '') {
          this.$message.error("请选择商品规格!");
          return
        }
        var cid = this.cid;
        var row = {
          specs: this.form.informantType,
          commodityName: this.shopdata.commodityName,
          commodityPicture: this.shopdata.commodityPicture,
          commodityImg: this.shopdata.commodityImg,
          commodityPrice: this.price,
          storeName: this.shopdata.storeName,
          storeId: this.shopdata.createUser,
          createUser:this.userData.id,
          updateUser:this.userData.id,
          commodityId: cid,
        }
        this.$http({
          method: "post",
          url:"/api/pxx-cart/cart/submit",
          data:JSON.stringify(row),
          headers: {'Content-Type': 'application/json'}
        }).then(() => {
          this.$message({
            type: "success",
            message: "加入购物车成功!"
          });
        }, error => {
          window.console.log(error);
        });

      },
      aaa(index) {
        this.shopdata.priceRange = this.shopdata.priceList[index],
                this.price = this.shopdata.priceList[index]
      },
      more() {
        this.activeName = 'second';
        this.activeData()
      },
      getCommodityData() {
        var id = this.cid;
        var storeId ='';
        this.$http({
          method:"get",
          url:"/api/pxx_commodity/commodity/getCommodityDetail",
          params: {
            id: id
          }
        }).then(res =>{
          this.shopdata = res.data.data;
          this.options = this.shopdata.specsList;
          const picture = this.shopdata.commodityPicture;
          this.list = picture.split(",");
          this.srcList.push('http://localhost:7777/'+this.shopdata.commodityImg);
          storeId = this.shopdata.createUser;
          var urlList = this.list
          for (let i = 0; i <urlList.length; i++) {
            this.urls.push('http://localhost:7777/'+urlList[i])
          }
        });
        this.$http({
          method:"get",
          url:"/api/pxx-store/store/detail",
          params: {
            loginId: this.shopdata.createUser
          }
        }).then(res =>{
          this.storeData = res.data.data
        });
      },
    }
  }
</script>

<style scoped>
  .talk_con {
    width: 90%;
    height: 500px;
    border: 1px solid #666;
    margin-top: -5%;
    background: #f9f9f9;
  }

  .talk_show {
    width: 90%;
    height: 420px;
    border: 1px solid #666;
    background: #fff;
    margin: 10px auto 0;
    overflow: auto;
  }

  .talk_input {
    width: 90%;
    margin: 10px auto 0;
  }
  .talk_word {
    width: 50%;
    height: 26px;
    padding: 0px;
    float: left;
    margin-left: 10px;
    outline: none;
    text-indent: 10px;
  }
  .talk_sub {
    width: 56px;
    height: 30px;
    float: left;
    margin-left: 10px;
  }

  .atalk span {
    display: inline-block;
    background: #0181cc;
    border-radius: 10px;
    color: #fff;
    padding: 5px 10px;
  }

  .btalk {
    margin: 10px;
    text-align: right;
  }

  .btalk span {
    display: inline-block;
    background: #ef8201;
    border-radius: 10px;
    color: #fff;
    padding: 5px 10px;
  }

  .mailTable {
    width: 100%;
    border-top: 1px solid #E6EAEE;
    border-left: 1px solid #E6EAEE;
  }

  .mailTable tr td {
    width: 200px;
    height: 35px;
    line-height: 35px;
    box-sizing: border-box;
    padding: 0 10px;
    border-bottom: 1px solid #E6EAEE;
    border-right: 1px solid #E6EAEE;
  }

  .mailTable tr td.column {
    background-color: #EFF3F6;
    color: #393C3E;
    width: 30%;
  }

  @keyframes addInCart {
    0% {
      transform: scale(1);
    }

    100% {
      transform: translateX(680px) translateY(-380px) scale(0.01);
    }
  }

  @keyframes addInOrder {
    0% {
      transform: scale(1);
    }

    100% {
      transform: translateX(620px) translateY(-380px) scale(0.01);
    }
  }
  @keyframes addInCollection {
    0% {
      transform: scale(1);
    }

    100% {
      transform: translateX(740px) translateY(-380px) scale(0.01);
    }
  }
</style>
